package thinkinjava4.ch12_exceptions;

class NeedsCleanup {
    private static long counter = 1;
    private final long id = counter++;

    public void dispose() {
        System.out.println("NeedsCleanup " + id + " disposed");
    }
}

class ConstructionException extends Exception {
}

class NeedsCleanup2 extends NeedsCleanup {
    public NeedsCleanup2() throws ConstructionException {
    }

    public NeedsCleanup2(boolean hasError) throws ConstructionException {
        if (hasError)
            throw new ConstructionException();
    }
}

public class CleanupIdiom {
    public static void error() {
        throw new RuntimeException();
    }

    public static void main(String[] args) {
        //Section 1:对象不会构造失败
        NeedsCleanup nc1 = new NeedsCleanup();
        try {
//            error();
        } finally {
            nc1.dispose();
        }

        //Section 2:对象不会构造失败，群组
        NeedsCleanup nc2 = new NeedsCleanup();
        NeedsCleanup nc3 = new NeedsCleanup();
        try {
//            error();
        } finally {
            nc3.dispose();
            nc2.dispose();
        }

        //Section 3:对象可能构造失败
        try {
            NeedsCleanup2 nc4 = new NeedsCleanup2();
            try {
//                error();
                NeedsCleanup2 nc5 = new NeedsCleanup2();
//                NeedsCleanup2 nc5 = new NeedsCleanup2(true);
                try {
//                    error();
                } finally {
                    nc5.dispose();
                }
            } catch (ConstructionException e) {
                e.printStackTrace(System.out);
            } finally {
                nc4.dispose();
            }
        } catch (ConstructionException e) {
            e.printStackTrace(System.out);
        }
    }
}
